//
//  PasswordManagerDataSource.swift
//  iTerm2SharedARC
//
//  Created by George Nachman on 3/18/22.
//

import Foundation

@objc
protocol PasswordManagerAccount: AnyObject {
    @objc var accountName: String { get }
    @objc var userName: String { get }
    @objc var displayString: String { get }
    @objc var hasOTP: Bool { get }
    @objc var sendOTP: Bool { get }

    @objc(fetchPasswordWithContext:completion:)
    func fetchPassword(context: RecipeExecutionContext,
                       _ completion: @escaping (String?, String?, Error?) -> ())

    @objc(setPasswordWithContext:password:completion:)
    func set(context: RecipeExecutionContext,
             password: String,
             completion: @escaping (Error?)-> ())

    @objc(deleteWithContext:completion:)
    func delete(context: RecipeExecutionContext,
                _ completion: @escaping (Error?) -> ())

    @objc(matchesFilter:) func matches(filter: String) -> Bool
}

@objc
protocol PasswordManagerDataSource: AnyObject {
    func fetchAccounts(context: RecipeExecutionContext, completion: @escaping ([PasswordManagerAccount]) -> ())
    var autogeneratedPasswordsOnly: Bool { get }
    func checkAvailability() -> Bool

    @objc(addUserName:accountName:password:context:completion:)
    func add(userName: String,
             accountName: String,
             password: String,
             context: RecipeExecutionContext,
             completion: @escaping (PasswordManagerAccount?, Error?) -> ())
    func resetErrors()
    func reload(_ completion: () -> ())
    func consolidateAvailabilityChecks(_ block: () -> ())

    @objc(toggleShouldSendOTPWithContext:forAccount:completion:)
    func toggleShouldSendOTP(context: RecipeExecutionContext,
                             account: PasswordManagerAccount,
                             completion: @escaping (PasswordManagerAccount?, Error?) -> ())

    @objc var canResetConfiguration: Bool { get }
    @objc func resetConfiguration()
    @objc var name: String { get }
    @objc var supportsMultipleAccounts: Bool { get }
    @objc(switchAccountWithCompletion:) func switchAccount(completion: @escaping () -> ())
}

extension PasswordManagerAccount {
    func _matches(filter: String) -> Bool {
        if filter.isEmpty {
            return true
        }
        return [accountName, userName].anySatisfies {
            $0.containsCaseInsensitive(filter)
        }
    }
}

